<script setup>
import LimitFram from "./LimitFrame.vue";
import ScSelector from "@/components/scSelector/ScSelector.vue";
import CanvasApi from "@/api/canvasApi.js";
import {
  deepClone,
  connectionsData,
  formatTimeStamp,
  formatTimeMs,
} from "@/utils";
const props = defineProps({
  limit: {
    type: Array,
    required: true,
  },
});
const blackGroupVisible = ref(false),
  form = ref({
    connection: "",
    groupId: "",
    keyValue: "",
    indicators: "",
    startTime: 0,
    endTime: 1,
    timeValue: "0",
    timeType: "1",
    propertyType: 0,
  }),
  blacklist = ref([]);
const timeList = ref([
  { name: "天", id: "1" },
  { name: "小时", id: "2" },
  { name: "分钟", id: "3" },
]);
const connectionList = ref(deepClone(connectionsData()));
const actConnection = ref([]);
const defaultTime = ref(new Date(2000, 1, 1, 23, 59, 59));
const indicatorsList = ref([
  { id: "actVisitFirstTime", name: "首次进入活动时间", type: 3 },
  { id: "actPartinCount", name: "活动参与次数", type: 0 },
  { id: "actPartinLastTime", name: "最近参与活动时间", type: 3 },
  { id: "actPartin", name: "是否参与活动", type: null },
  { id: "actOrderCount", name: "活动订单数", type: 0 },
]);
const bloList = ref([
  { name: "是", id: "true" },
  { name: "否", id: "false" },
]);
const formRef = ref();
const emits = defineEmits(["cancel"]);

const rules = {
  groupId: [{ required: true, message: "请选择活动", trigger: "change" }],
  connection: [{ required: true, message: "请选择连接关系", trigger: "blur" }],
  keyValue: [
    { required: true, message: "请填写判断值", trigger: ["change", "blur"] },
  ],
  indicators: [{ required: true, message: "请选择活动指标", trigger: "blur" }],
  startTime: [{ required: true, message: "请填写时间", trigger: "blur" }],
  endTime: [{ required: true, message: "请填写时间", trigger: "blur" }],
};

// 描述
const ruleText = computed(() => {
  let rule = props.limit.value;

  if (!rule.groupId) return "";
  let connectionData = "";
  let describe = "";

  if (rule.propertyType == null) {
    describe = `“${rule.keyValue == "true" ? "参与活动" : "不参与活动"}”`;
  } else {
    // 获取连接符
    connectionData = actConnection.value.find(
      (item) => item.id == rule.connection
    );
    describe = `“${rule.indicsName}” ${connectionData?.name} ${rule.keyValue}`;
  }

  if (rule.propertyType == 3) {
    let timeData = timeList.value.find((item) => item.id == rule.timeType); // 获取时间单位 天内 or 时内 or 分内
    if (rule.timeValue == 0) {
      if (rule.connection == "true") {
        describe = `“${rule.indicsName}” ${rule.startTime} ~ ${rule.endTime} ${timeData.name}`;
      } else {
        describe = `“${rule.indicsName}” ${connectionData?.name}  ${rule.startTime} ${timeData.name}`;
      }
    } else {
      if (rule.connection == "true") {
        describe = `${rule.startTime} ≤ “${rule.indicsName}” ≤ ${rule.endTime}`;
      } else {
        describe = `“${rule.indicsName}” ${connectionData?.name} ${rule.startTime}`;
      }
    }
  }
  return `${rule.actName} ${describe}`;
});

// 获取活动数据
const getActivityList = async () => {
  const rs = await CanvasApi.getActivityList({
    currentPage: 1,
    showCount: -1,
  });
  if (rs.code == 200) {
    blacklist.value = rs.payload.map((item) => {
      return { value: item.id, label: item.name };
    });
  }
};

const getBlackKeys = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      props.limit.value = deepClone(form.value);
      formatLimit();
      blackGroupVisible.value = false;
    }
  });
};

// 生成表达式
const formatLimit = () => {
  // 表达式最终的样子
  // $_act.actPartinCount$$_1 >= 3

  // props.limit.propertyKey = "userGroup";
  // props.limit.propertyType = 0;
  // props.limit.businessType = "userGroup";
  // 时间
  let expression = "";
  // let sentencedToEmpty = `$_act.${form.value.indicators}$$_${form.value.groupId} != null &&`; // 表达式判空
  let limtKeys = [
    {
      businessType: "act",
      key: `${form.value.indicators}$$_${form.value.groupId}`,
      obj: [form.value.groupId],
    },
  ];
  if (form.value.propertyType == 3) {
    limtKeys.push({
      businessType: "system",
      key: `currentTime`,
      obj: "",
    });
    if (form.value.timeValue == 0) {
      if (form.value.connection == "true") {
        expression = `($_act.${form.value.indicators}$$_${
          form.value.groupId
        }>=($_system.currentTime-${formatTimeMs(
          form.value.endTime,
          form.value.timeType
        )}) && $_act.${form.value.indicators}$$_${
          form.value.groupId
        }<=($_system.currentTime-${formatTimeMs(
          form.value.startTime,
          form.value.timeType
        )}))`;
      } else {
        expression = `$_act.${form.value.indicators}$$_${form.value.groupId}${
          form.value.connection
        }($_system.currentTime-${formatTimeMs(
          form.value.startTime,
          form.value.timeType
        )})`;
      }
    } else {
      if (form.value.connection == "true") {
        expression = `($_act.${form.value.indicators}$$_${
          form.value.groupId
        }>=${formatTimeStamp(form.value.startTime)} && $_act.${
          form.value.indicators
        }$$_${form.value.groupId}<=${formatTimeStamp(form.value.endTime)})`;
      } else {
        expression = `$_act.${form.value.indicators}$$_${form.value.groupId}${
          form.value.connection
        }${formatTimeStamp(form.value.startTime)}`;
      }
    }
  } else {
    if (form.value.propertyType == null) {
      form.value.connection = "==";
      expression = `$_act.${form.value.indicators}$$_${form.value.groupId}${form.value.connection}${form.value.keyValue}`;
    } else {
      expression = `$_act.${form.value.indicators}$$_${form.value.groupId}${form.value.connection}'${form.value.keyValue}'`;
    }
  }

  props.limit.keys = limtKeys;
  props.limit.expression = expression;
};

const addRule = () => {
  if (formRef.value) formRef.value.resetFields();
  blackGroupVisible.value = true;
};

const editRule = () => {
  form.value = deepClone(props.limit.value);

  tiemRadioChange(form.value.propertyType);
  blackGroupVisible.value = true;
};

const onClose = () => {
  emits("cancel");
};

const onChangeAct = (val) => {
  form.value.actName = val.selected[0].title;
};

const tiemValueRadioChange = (val) => {
  if (val == 0) {
    form.value.startTime = 0;
    form.value.endTime = 1;
  } else {
    form.value.startTime = "";
    form.value.endTime = "";
  }
  tiemRadioChange(form.value.propertyType);
};

// 相对时间变化时修改为对应的关系
const tiemRadioChange = (val) => {
  if (form.value.propertyType == null) {
    return;
  }
  actConnection.value = connectionList.value[val].list;
};
// 切换时修改连接关系
const onChangeIndicators = (val) => {
  form.value.keyValue = "";
  let group = indicatorsList.value.find((item) => item.id == val);
  if (group) {
    form.value.indicsName = group.name;
    form.value.connection = "";
    form.value.propertyType = group.type;
    tiemRadioChange(group.type);
  }
};
onMounted(() => {
  // getActivityList();
  tiemRadioChange(form.value.propertyType);
});

defineExpose({ add: addRule });
</script>
<template>
  <LimitFram title="活动数据" :content="ruleText" @edit="editRule" />
  <Dialog
    v-model="blackGroupVisible"
    title="活动数据"
    :width="700"
    @confirm="getBlackKeys"
    @close="onClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-position="top"
      label-width="auto"
    >
      <el-form-item label="选择活动" prop="groupId">
        <!-- <el-select-v2
          v-model="form.groupId"
          :options="blacklist"
          filterable
          placeholder="请选择活动"
          @change="onChangeAct"
        /> -->
        <ScSelector
          v-model="form.groupId"
          type="activity"
          @change-selected="onChangeAct"
        >
          <template #expand-pop="{ data }">
            <div v-if="data" class="detail-container">
              <div class="detail-text">
                <h3>
                  {{ data.info.name }}
                  <el-tag
                    :type="
                      data.info.status == 2 || data.info.status == 1
                        ? ''
                        : 'danger'
                    "
                    >{{
                      data.info.status == 2
                        ? "已上线"
                        : data.info.status == 1
                        ? "预上线"
                        : "已下线"
                    }}</el-tag
                  >
                </h3>
                <div class="detail-text_line">
                  开始时间：{{ $filters.dateFormat(data.info.startTime) }}
                </div>
                <div class="detail-text_line">
                  结束时间：
                  {{ $filters.dateFormat(data.info.endTime) }}
                </div>
                <div class="detail-text_line">
                  所属机构：
                  {{ data.info.insName }}
                </div>
                <div>
                  所属分组：
                  {{ data.info.groupName || "全部" }}
                </div>
                <div>
                  活动备注：
                  {{ data.info.remark || "暂无" }}
                </div>
              </div>
              <div class="detail-img" v-if="data.info.coverUrl">
                <img :src="data.info.coverUrl" alt="" />
              </div>
            </div>
          </template>
        </ScSelector>
      </el-form-item>
      <el-form-item label="活动指标" prop="indicators">
        <el-select
          v-model="form.indicators"
          placeholder="请选择活动指标"
          @change="onChangeIndicators"
        >
          <el-option
            v-for="item in indicatorsList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        v-if="!(form.propertyType == null)"
        label="连接关系"
        prop="connection"
      >
        <el-select v-model="form.connection" placeholder="请选择连接关系">
          <el-option
            v-for="item in actConnection"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <!-- 数字 -->
      <el-form-item
        v-if="form.propertyType == 0"
        label="判断值"
        prop="keyValue"
      >
        <el-input-number
          v-model="form.keyValue"
          :min="1"
          :max="99999999"
          controls-position="right"
          placeholder="请填写判断值"
        />
      </el-form-item>

      <!-- 布尔 -->
      <el-form-item
        v-if="form.propertyType == null"
        label="判断值"
        prop="keyValue"
      >
        <el-select v-model="form.keyValue" placeholder="请选择判断值">
          <el-option
            v-for="item in bloList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <!-- 时间 -->
      <template v-if="form.propertyType == 3">
        <el-form-item label="判断值" prop="radio">
          <el-radio-group
            v-model="form.timeValue"
            @change="tiemValueRadioChange"
          >
            <el-radio label="0">相对时间</el-radio>
            <el-radio label="1">固定时间 </el-radio>
          </el-radio-group>
        </el-form-item>

        <div class="time-class" v-if="form.timeValue == 0">
          <el-form-item prop="startTime">
            <el-input-number
              v-model="form.startTime"
              :min="0"
              :max="99999999"
              controls-position="right"
            />
          </el-form-item>
          <div v-if="form.connection == 'true'">_</div>
          <el-form-item v-if="form.connection == 'true'" prop="endTime">
            <el-input-number
              v-model="form.endTime"
              :min="1"
              :max="99999999"
              controls-position="right"
            />
          </el-form-item>

          <el-form-item class="time-list" prop="radio">
            <el-select v-model="form.timeType" placeholder="请选择">
              <el-option
                v-for="item in timeList"
                :value="item.id"
                :label="item.name"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="time-class" v-if="form.timeValue == 1">
          <el-form-item prop="startTime">
            <el-date-picker
              v-model="form.startTime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetime"
              placeholder="请选择时间"
            />
          </el-form-item>
          <div v-if="form.connection == 'true'">_</div>
          <el-form-item prop="endTime" v-if="form.connection == 'true'">
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择时间"
              :default-time="defaultTime"
            />
          </el-form-item>
        </div>
      </template>
    </el-form>
  </Dialog>
</template>

<style lang="scss" scoped>
.el-select-v2 {
  min-width: 440px;
}

.time-class {
  display: flex;
  * {
    margin-right: 10px;
  }
}
.el-select,
.el-input {
  width: 440px;
}
.time-list .el-select {
  width: 208px;
}

.detail-container {
  display: flex;
  .detail-text_line {
    white-space: nowrap;
  }
  .detail-img {
    margin-left: 10px;
    width: 200px;
    height: 260px;
    overflow: hidden;
    flex-shrink: 0;
    img {
      display: block;
      width: 100%;
    }
  }
}
</style>
